package com.spt.springbootzhsx.service.suggest.Get_MovieToMovieCounts_3;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class GetMTMC_Reducer extends Reducer<Text, Text, Text, Text> {
    private Map<String, Integer> map = new HashMap<String, Integer>();
    private StringBuffer sb = new StringBuffer();
    private Text outV = new Text();

    @Override
    protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
        for (Text val : values) {
            if (map.containsKey(val.toString())){
                //如果map中包含该键
                map.put(val.toString(),map.get(val.toString())+1);
            }else {
                map.put(val.toString(),1);
            }
        }

        //拼接字符串
        for (Map.Entry<String, Integer> en : map.entrySet()) {
            sb.append(en.getKey()).append(":").append(en.getValue()).append(",");
        }
        //去除末尾的“，”
        sb.setLength(sb.length()-1);
        outV.set(sb.toString());

        context.write(key,outV);

        sb.setLength(0);
        map.clear();
        outV.clear();
    }
}
